#include<iostream>
#include<fstream>
#include<cstdlib>
#include "../EdgeDetection.h"
#include "../LFOSCommon.h"

using namespace std;

int copyHeader(ifstream& input, ofstream& output);

int main3(int argc, char* argv[])
{
	EdgeDetection ed;
	unsigned char inBuffer[PIXELS];
	unsigned char image[PIXELS];
	bool* edgeImage;
	unsigned char buffer[PIXELS];
	unsigned char outBuffer[PIXELS];
	int nColors;
	ifstream inFile;
	ofstream outFile;

	if(argc != 3)
	{
		cout << "Usage: EdgeDetectionTest <input image> <output image>\n";
		exit(1);
	}

	inFile.open(argv[1], ios::in | ios::binary);
	if(inFile.fail())
	{
		cout << argv[1] << " does not exist\n";
		exit(1);
	}

	outFile.open(argv[2], ios::out | ios::binary);
	if(outFile.fail())
	{
		cout << "Error opening " << argv[2] << endl;
		exit(1);
	}

	nColors = copyHeader(inFile, outFile);

	inFile.seekg(54+4*nColors);
	outFile.seekp(54+4*nColors);

	inFile.read((char*)inBuffer, PIXELS);


	//image stored upside down - need to invert rows
	for(int y=0; y < ROWS; y++)
		for(int x=0; x < COLS; x++)
		{
			image[ROW_COL_TO_INDEX(x,ROWS-y-1)] = inBuffer[ROW_COL_TO_INDEX(x,y)];
		}

	edgeImage = ed.ProcessEdges(image);

    for(int x=0; x < PIXELS; x++)
    {
    	if(edgeImage[x])
    		buffer[x] = 255;
    	else
    		buffer[x] = 0;
    }


    //invert rows again for storage
	for(int y=0; y < ROWS; y++)
		for(int x=0; x < COLS; x++)
		{
			outBuffer[ROW_COL_TO_INDEX(x,ROWS-y-1)] = buffer[ROW_COL_TO_INDEX(x,y)];
		}
    outFile.write((char*)outBuffer, PIXELS);

	inFile.close();
	outFile.close();

	cout << "Edge Detection Test Complete" << endl;

	return 0;
}

int copyHeader(ifstream& input, ofstream& output)
{
	int nColors;
	unsigned char buffer[1024];

	//read number of colors
	input.seekg(46);
	input.read((char*)buffer, 4);
	nColors = buffer[0] | (buffer[1] << 8) |
			(buffer[2] << 16) | (buffer[3] << 24);

	//copy header
	input.seekg(0);
	output.seekp(0);
	input.read((char*)buffer, 50);
	output.write((char*)buffer, 50);

	//copy color table
	input.seekg(54);
	output.seekp(54);
	input.read((char*)buffer, 4*nColors);
	output.write((char*)buffer, 4*nColors);

	return nColors;
}
